﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using CoreEx.Database.Metadata;
using CoreEx.Common.Extensions;
using System.Runtime.Serialization.Formatters.Binary;
using LinFu.IoC.Configuration;

namespace CoreEx.Database.MetaData.Implementation
{
    [Implements(typeof(IRepositoryStorage))]
    
    public class RepositoryStorage : IRepositoryStorage
    {
        private static string _lockObject = "lock";

        public IMetadataRepository Load(string name)
        {
            lock (_lockObject)
            {
                string path = GetRepositoryPath(name);
                if (Contains(name))
                {
                    using (FileStream fileStream = new FileStream(path, FileMode.Open))
                    {
                        BinaryFormatter formatter = new BinaryFormatter();
                        IMetadataRepository storedRepository = (IMetadataRepository) formatter.Deserialize(fileStream);
                        return storedRepository;
                    }
                }
                return null;
            }
        }

        
        public void Save(IMetadataRepository repository)
        {
            lock(_lockObject)
            {
                using (FileStream fileStream = new FileStream(GetRepositoryPath(repository.Name), FileMode.OpenOrCreate)
                    )
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(fileStream, repository);
                }
            }
        }
        
        public bool Contains(string name)
        {
            return File.Exists(GetRepositoryPath(name));
        }

        
        protected virtual string GetRepositoryPath(string name)
        {
            return Path.Combine(typeof(RepositoryStorage).Assembly.GetDirectory(),
                                         string.Format("{0}Metadata.dat", name));

        }
    }
}